from itsdangerous import TimedJSONWebSignatureSerializer as Secret # 注意别名冲突
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse, JsonResponse
from PIL import Image, ImageDraw, ImageFont
from django.utils.six import BytesIO
from django.views.generic import View
from django.contrib.auth import login, logout, authenticate
import re
from user.models import User, Address
from Computer import settings
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import make_password
from utils.LoginRequremixIn import LoginRequireMixIn
from django_redis import get_redis_connection
from goods.models import Goods
from order.models import OrderGoods, OrderInfo
from celery_tasks.task import send_active_mail
# 验证码模块
def verify_code(request):

    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象，ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
    font = ImageFont.truetype('Arial', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str.upper()
    #内存文件操作
    buf = BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')




class Login(View):
    def get(self, request):
        if 'username' in request.COOKIES:
            username = request.COOKIES.get('username')
            checked = 'checked'
            return render(request, 'login.html', {'username': username, 'checked': checked})
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get('phone')
        verify = request.POST.get('verify')
        pwd = request.POST.get('pwd')
        remember = request.POST.get('remember')

        if verify.upper() != request.session['verifycode'].upper():
            return render(request, 'login.html', {'err': '验证码错误'})
        if not all([username, verify, pwd]):
            return render(request, 'login.html',  {'err': '数据不完整'})
        try:
            user = User.objects.get(username=username)

            if not user.is_active:

                self.activation(user)
                return render(request, 'login.html', {'err': '用户未激活,激活链接已发送到您的邮箱，请点击已激活密码'})
            # 这里面有一个坑，就是要检验is_active，判断密码是不是生效
            user = authenticate(username=username, password=pwd)
        except:
            user = None
        if user is not None:
            login(request, user)
            # 获取跳转地址，默认为index
            next_url = request.GET.get('next', reverse('goods:index'))
            response = redirect(next_url)
            if remember == 'on':
                response.set_cookie('username', username, max_age=7*24*3600)
            else:
                response.delete_cookie('username')
            return response
        else:
            return render(request, 'login.html', {'err': '账户或密码错误'})


#  用于激活密码

    @staticmethod
    def activation(u):
        secret_key = Secret(settings.secret_key, 3600)
        info = {'confirm': u.id}
        token = secret_key.dumps(info)
        token = token.decode()

        send_active_mail(u, token)





# 用户解密激活
def decrypt(request, token):
    print(token)
    secretKey = Secret(settings.secret_key, 3600)

    try:
        info = secretKey.loads(token)
        user_id = info['confirm']
        user = User.objects.get(id=user_id)
        user.is_active = 1
        user.save()
        return redirect(reverse('user:login'))
    except:
        return HttpResponse('激活链接已过期，请到登录界面重新获取激活权限')


def register(request):

    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        username = request.POST.get('phone')
        usermail = request.POST.get('mail')
        verify = request.POST.get('verify')
        pwd = request.POST.get('pwd')
        repwd = request.POST.get('repwd')
        promise = request.POST.get('help')
        context = {
            'username': username,
            'usermail': usermail,
            'verify': verify,
            'pwd': pwd,
            'repwd': repwd,
            'promise': promise,
            'err': ''
        }

        if not all([usermail, username, verify, pwd, repwd, promise]):
            context['err'] = '数据不完整!'
            return render(request, 'register.html', context)

        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', usermail):
            context['err'] = '邮箱格式错误!'
            return render(request, 'register.html', context)
        if promise != 'on':
            context['err'] = '请先同意条款!'
            return render(request, 'register.html', context)
        try:
            user = User.objects.filter(Q(username=username) | Q(email=usermail))
        except User.DoesNotExist:
            user = None
        if user:
            context['err'] = '用户已存在!'
            return render(request, 'register.html', context)
        if pwd != repwd:
            context['err'] = '密码不一致!'
            return render(request, 'register.html', context)

        if verify.upper() != request.session['verifycode']:
            context['err'] = '验证码错误!'
            return render(request, 'register.html', context)
        user = User.objects.create_user(username, usermail, pwd)
        user.is_active = 0
        user.save()
        return redirect('user:login')

# 找回密码
class Findpwd(View):
    def get(self, request):
        return render(request, 'find_pwd.html')


@csrf_exempt
def secret(request):
    mail = request.POST.get('mail')
    request.session['secret_key'] = send_active_mail.delay(mail)

    return JsonResponse({'res': '发送成功'})


# 用ajax提交避免不必要的刷新，把表单信息保留到表单中，不影响用户体验
@csrf_exempt
def ajax_fand_pwd(request):
    mail = request.POST.get('mail')
    secret = request.POST.get('secret')
    pwd = request.POST.get('pwd')
    repwd = request.POST.get('repwd')
    context = {'err': ''}
    if not all([mail, secret, pwd, repwd]):
        context['err'] = '数据不完整'
    if repwd == pwd:
        context['err'] = '密码不一致'
    if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', mail):
        context['err'] = '邮箱格式错误!'
    try:
        test = request.session['secret_key']
        if test != secret:
            context['err'] = '密钥不正确'

        if test == secret:
            user = User.objects.get(email=mail)
            if user is not None:
                user.password = make_password(repwd)
                user.save()
                del request.session['secret_key']
                context['err'] = '修改生效, 密钥失效'
    except KeyError as e:
        context['err'] = '密钥无效'

    return JsonResponse(context)


class LoginOut(View):
    def get(self, request):
        logout(request)
        return redirect('goods:index')


class User_info(LoginRequireMixIn, View):

    def get(self, request):
        user = request.user
        cart_key = 'cart_%d'%user.id
        con = get_redis_connection('default')
        history_key = 'history_%d' %user.id
        goods_id = con.lrange(history_key, 0, 5)
        goods_lis = Goods.objects.filter(id__in=goods_id)
        cart_count = con.hlen(cart_key)

        # 获取用户的订单
        orders = OrderInfo.objects.filter(user=user).order_by('-create_time')

        for order in orders:

            order_goods = OrderGoods.objects.filter(order=order.order_id)
            order.order_goodes = order_goods
            order.order_status_name = OrderInfo.ORDER_STATUS[order.order_status]





        context = {'username': user.username, 'res': goods_lis, 'orders': orders, 'cart_count': cart_count,
}







        return render(request, 'user.html', context)












    # def post(self, request):
    #     user = request.user
    #     username = request.POST.get('username', user.username)
    #     reciver = request.POST.get('reciver')
    #     addr = request.POST.get('addr', '')
    #     mail = request.POST.get('mail', '')
    #     tel = request.POST.get('tel', '')
    #     if not all([username, reciver, addr, mail, tel]):
    #         return render(request, 'user.html', {'err': '数据不完整'})
    #
    #     if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', mail):
    #         return render(request, 'user.html', {'err': '邮箱格式错误'})
    #     try:
    #         userd = User.objects.filter(username=username)
    #     except User.DoesNotExist:
    #         userd = None
    #     if userd:
    #         if username != user.username:
    #             return render(request, 'user.html', {'err': '用户名已存在'})
    #     if not re.match(r"^1[35678]\d{9}$", tel):
    #         return render(request, 'user.html', {'err': '手机格式错误'})
    #     addre = Address.object.get_dafult_add(user)
    #     if addre == 'None':
    #         Address.objects.create(user=user, reciver=reciver, addr=addr, mail=mail, tel=tel)
    #     user_addr = Address.objects.get(user=user)
    #     user.username = username
    #     user_addr.reciver = reciver
    #     user_addr.addr = addr
    #     user_addr.mail = mail
    #     user_addr.tel = tel
    #     user_addr.save()
    #     user.save()
    #     return redirect(reverse('user:user_info'))# get请求

